#![allow(non_snake_case)]

use std::{ffi::c_void, ptr, thread};

use android_logger::Config;
use jni::{
    objects::JClass, sys::{jint, jstring, JNI_VERSION_1_6}, JNIEnv, JavaVM
};
use log::{debug, LevelFilter};


mod raw_serial_port;
mod serial_port;
mod serial_port2;
mod service;

pub use serial_port::*;
pub use serial_port2::*;
pub use service::*;

use crate::{error::AppErr, utils::{get_mac_address, global::{self}, path::{self, IO_EXCEPTION}}};

#[no_mangle]
pub extern "system" fn JNI_OnLoad(vm: JavaVM, _: *mut c_void) -> jint {
    global::init(vm);

    android_logger::init_once(
        Config::default()
            .with_max_level(LevelFilter::Debug)
            .with_tag("native log"),
    );

    path::init().unwrap();

    debug!("JNI_Onload");

    JNI_VERSION_1_6
}

#[no_mangle]
pub extern "system" fn Java_rustlib_CoreKt_getUniqueId(
    mut env: JNIEnv,
    _clz: JClass
) -> jstring {

    fn call_impl(env: &mut JNIEnv) -> Result<jstring, AppErr> {
        let mac_addr = get_mac_address(MAC_NAME)?;
        let addr = env.new_string(mac_addr)?;
        Ok(addr.as_raw())
    }

    match call_impl(&mut env) {
        Ok(s) => return s,
        Err(e) => {
            _ = env.throw_new(IO_EXCEPTION, e.to_string());

        }
    }

    return ptr::null_mut();
}










